package com.huayi.test.springbootcomm.trans.service;

import com.alibaba.fastjson.JSONObject;
import com.huayi.test.springbootcomm.constant.ErrCodeInfo;
import com.huayi.test.springbootcomm.dao.*;
import com.huayi.test.springbootcomm.entity.*;
import com.huayi.test.springbootcomm.exception.BizException;
import com.huayi.test.springbootcomm.service.IserviceContext;
import com.huayi.test.springbootcomm.util.BigdecimalUtil;
import com.huayi.test.springbootcomm.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.rmi.runtime.Log;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Service("t40105")
public class T40105Service extends BaseService {
    private static final Logger LOG = LoggerFactory.getLogger(T40105Service.class);

    @Autowired
    private TblHuayiGoodsMapper tblHuayiGoodsMapper;
    @Autowired
    private TblHuayiGoodsHisMapper tblHuayiGoodsHisMapper;
    @Autowired
    private TblBuyTransMapper tblBuyTransMapper;
    @Autowired
    private TblSaleTransMapper tblSaleTransMapper;
    @Autowired
    private TblSystemDateMapper tblSystemDateMapper;
    @Autowired
    private TblSystemParaMapper tblSystemParaMapper;

    @Override
    public void action(IserviceContext context) throws Exception {
        LOG.info("交易 40105  开始执行>>>>>>>>>>>>>>>>>>>>>>>>>>");
        JSONObject body = JSONObject.parseObject(context.getReqMap().get("body").toString());
        String tranDt = body.getString("tranDt");

        // 查询当前系统日期
        TblSystemDateExample example = new TblSystemDateExample();
        List<TblSystemDate> tblSystemDateList = tblSystemDateMapper.selectByExample(example);
        TblSystemDate tblSystemDate = tblSystemDateList.get(0);
        String sysDate = tblSystemDate.getTranDate();
        String lastTranDate = tblSystemDate.getLastTranDate();
        LOG.debug("当前系统日期：[{}]", sysDate);
        LOG.debug("前一日系统日期[{}]",lastTranDate);
        if (!tranDt.equals(sysDate)) {
            throw new BizException("EXP.1001", "传入日期与当前日期不相等,传入日期【" + tranDt + "】系统日期【" + sysDate + "】");
        }
        // 查询库存表
        TblHuayiGoodsExample tblHuayiGoodsExample = new TblHuayiGoodsExample();
        tblHuayiGoodsExample.createCriteria().andTranDtEqualTo(lastTranDate);
        List<TblHuayiGoods> tblHuayiGoods = tblHuayiGoodsMapper.selectByExample(tblHuayiGoodsExample);
        LOG.debug("当天有【{}】条数据戴处理", tblHuayiGoods.size());
        // 1. 存入历史表数据
        TblHuayiGoodsHis tblHuayiGoodsHis = null;
        for (TblHuayiGoods item : tblHuayiGoods) {
            tblHuayiGoodsHis = new TblHuayiGoodsHis();
            BeanUtils.copyProperties(item, tblHuayiGoodsHis);
            tblHuayiGoodsHis.setId(0L);
            tblHuayiGoodsHisMapper.insert(tblHuayiGoodsHis);
        }

        // 2. 更新库存表数据（先增加库存，然后进行减库存操作,减为负数的需要进行返回提示）
        Map<String, Object> errMap = goodsCalculate(lastTranDate, sysDate);

        // 3.切日
        updateSystemDate();

        Map<String, Object> respMap = context.getRespMap();
        respMap.put("errMap",errMap);
        respMap.put("respCode", ErrCodeInfo.SUCCESS.getErrCode());
        respMap.put("respMsg",ErrCodeInfo.SUCCESS.getErrMsg());
        LOG.info("交易 40105  执行结束<<<<<<<<<<<<<<<<<<<<<<<<<<");
    }

    /**
     * 切日
     *
     * @return
     */
    private void updateSystemDate() throws Exception {
        LOG.info("切日组件开始>>>>>>>>>>>>>>>>>>>>>>>>>>");
        // 查询当前系统日期
        TblSystemDateExample example = new TblSystemDateExample();
        List<TblSystemDate> tblSystemDateList = tblSystemDateMapper.selectByExample(example);
        TblSystemDate tblSystemDate = tblSystemDateList.get(0);
        String tranDate = tblSystemDate.getTranDate();
        LOG.debug("当前系统日期：[{}]", tranDate);
        LOG.debug("切日后的系统日期为:[{}]", tblSystemDate.getNextTranDate());
        TblSystemDate tblSystemDateUpdate = new TblSystemDate();
        tblSystemDateUpdate.setId(tblSystemDate.getId());
        tblSystemDateUpdate.setLastTranDate(tblSystemDate.getTranDate());
        tblSystemDateUpdate.setTranDate(tblSystemDate.getNextTranDate());
        tblSystemDateUpdate.setNextTranDate(DateUtil.getSpecifiedDayAfter(tblSystemDate.getNextTranDate()));

        int i = tblSystemDateMapper.updateByPrimaryKeySelective(tblSystemDateUpdate);
        LOG.info("更新系统日期结束,受影响条数:[{}]", i);

        // 每次跑完需要在参数表中
        TblSystemPara tblSystemPara = new TblSystemPara();
        tblSystemPara.setParamId(tranDate);
        tblSystemPara.setParamValue("已更新");
        try {
            tblSystemParaMapper.insert(tblSystemPara);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BizException("EXP.10030", "数据插入异常");
        }
    }



    /**
     * 处理交易日的加减库存处理，
     * 1.先增加库存，在减少库存
     * 2. 返回有异常的型号 ，数量异常 ， 重量异常
     *
     * @param lastTranDate
     */
    private Map<String, Object> goodsCalculate(String lastTranDate,String sysDate) {
        LOG.info("开始计算处理[{}]的库存>>>>>>>>>>>>>>>>>>>");
        LOG.debug("lastTranDate=["+lastTranDate+"],sysDate=["+sysDate+"]");
        List<String> kinds = new LinkedList<>();
        kinds.add("FG");
        kinds.add("YG");
        kinds.add("BG");
        // 对于有异常信息的map进行返回
        Map<String,Object> expMap = new HashMap<>();
        // 1. 查询进货数据-查询当天处理的
        TblBuyTransExample buyTransExample = new TblBuyTransExample();
        buyTransExample.createCriteria().andTranDtEqualTo(sysDate);
        List<TblBuyTrans> tblBuyTrans = tblBuyTransMapper.selectByExample(buyTransExample);
        LOG.debug("进货条目：[{}]", tblBuyTrans.size());

        // 查询棺材类库存，查询上一天的
        TblHuayiGoodsExample tblHuayiGoodsExample = new TblHuayiGoodsExample();
        tblHuayiGoodsExample.createCriteria().andTranDtEqualTo(lastTranDate).andKindsIn(kinds);
        List<TblHuayiGoods> tblHuayiGoodList = tblHuayiGoodsMapper.selectByExample(tblHuayiGoodsExample);
        LOG.debug("管材类库存条目：[{}]", tblHuayiGoodList.size());

        // 查询型材类库存，查询上一天的
        TblHuayiGoodsExample tblHuayiGoodsExample2 = new TblHuayiGoodsExample();
        tblHuayiGoodsExample2.createCriteria().andTranDtEqualTo(lastTranDate).andKindsEqualTo("QT");
        List<TblHuayiGoods> tblHuayiGoodList2 = tblHuayiGoodsMapper.selectByExample(tblHuayiGoodsExample2);
        LOG.debug("型材类库存条目：[{}]", tblHuayiGoodList2.size());


        TblSaleTransExample saleTransExample = new TblSaleTransExample();
        saleTransExample.createCriteria().andTranDtEqualTo(sysDate);
        List<TblSaleTrans> tblSaleTransList = tblSaleTransMapper.selectByExample(saleTransExample);
        LOG.debug("出库条目：[{}]", tblSaleTransList.size());

        int num = 0;
        for (TblHuayiGoods item : tblHuayiGoodList) {// 循环库存进行,进行加减库存-对于管材类
            num++;
            String specification = item.getSpecification();//型号
            String thickness = item.getThickness();//厚度
            TblHuayiGoods updateModel = new TblHuayiGoods();
            LOG.debug("棺材类更新，更新第["+num+"]条,型号=["+specification+"],厚度=["+thickness+"]");
            BeanUtils.copyProperties(item, updateModel);
            // 加库存,更新成本单价，更新吨位价，更新重量
            for (TblBuyTrans buyTrans : tblBuyTrans) {
                // 满足条件更新最新值
                if (specification.equals(buyTrans.getSpecification()) && thickness.equals(buyTrans.getThickness())) {
                    LOG.debug("开始加库存，型号:[" + specification + "],厚度:[" + thickness + "]");
                    updateModel.setTotalQuanlity(item.getTotalQuanlity() + buyTrans.getQuanlity());// 数量增加
                    updateModel.setWeightRencently(buyTrans.getWeightPer());

                    updateModel.setCostPrice(buyTrans.getCostPrice());// 成本
                    updateModel.setTonOfPriceRerently(buyTrans.getWeightPer().add(buyTrans.getFee()).multiply(new BigDecimal("1000")));
                    updateModel.setManufacturerName(buyTrans.getCompany());// 进货厂商
                    updateModel.setBuyDateRecently(sysDate);// 本次到货日期
                    updateModel.setQuanlityAddRecently(buyTrans.getQuanlity());// 本次新增数量
                    updateModel.setQuanlityPerRecently(buyTrans.getQuantityPer());// 单件支数
                    if (BigdecimalUtil.judgeBigOrSmall(buyTrans.getWeightPer(), item.getWeightRencently())) {// 历史最重重量
                        updateModel.setWeightPerHis(buyTrans.getWeightPer());
                    }

                    updateModel.setLastPrice(item.getCostPrice());// 上次进货成本价格
                    updateModel.setLastQuanlity(item.getTotalQuanlity());//上次剩余数量
                    updateModel.setLastBuyDate(item.getBuyDateRecently());// 上次购买日期
                    updateModel.setLastTonOfPrice(item.getTonOfPriceRerently());// 上次吨位价
                    updateModel.setLastManufacturerName(item.getManufacturerName());// 上次进货厂商
                    updateModel.setLastQuanlityPer(item.getQuanlityPerRecently());// 上次单件支数
                }
            }
            // 减库存
            for (TblSaleTrans saleTrans : tblSaleTransList) {
                if (specification.equals(saleTrans.getSpecification()) && thickness.equals(saleTrans.getThickness())) {
                    updateModel.setTotalQuanlity(updateModel.getTotalQuanlity() - saleTrans.getQuanlity());// 减库存
                }
            }
            // 通用只更新交易日期
            updateModel.setTranDt(sysDate);
            int i = tblHuayiGoodsMapper.updateByPrimaryKeySelective(updateModel);
            LOG.debug("更新库存表，受影响行数:[{}]",i);

            if (updateModel.getTotalQuanlity()<0){
                String key = updateModel.getSpecification()+"_"+updateModel.getTotalQuanlity();
                String errMsg = "该型号数量小于0";
                expMap.put(key,errMsg);
            }

        }

        return expMap;
    }
}
